package com.aaa.mrcai.service.impl;

import com.aaa.mrcai.mapper.GoodsBrandMapper;
import com.aaa.mrcai.pojo.entity.GoodsBrand;
import com.aaa.mrcai.pojo.vo.GoodsBrandVo;
import com.aaa.mrcai.query.GoodsBrandQuery;
import com.aaa.mrcai.result.AjaxResult;
import com.aaa.mrcai.service.GoodsBrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Demo class
 *
 * @Author: Wang
 * @Date: Created in 0:07 2021/12/7
 */
@Service
public class GoodsBrandServiceImpl implements GoodsBrandService {
    @Autowired
    private GoodsBrandMapper goodsBrandMapper;

    @Autowired
    private ServletContext servletContext;


    @Override
    public AjaxResult list(GoodsBrandQuery query) {
        List<GoodsBrand> goodsBrandList = goodsBrandMapper.queryGoodsBrand(query);
        Long totalCount = goodsBrandMapper.queryGoodsBrandTotalCount(query);

        Map<Object, Object> map = new HashMap<>();
        map.put("currentPageData",goodsBrandList);
        map.put("currentDataTotal", totalCount);
        return AjaxResult.success(map);
    }

    @Override
    public AjaxResult addGoodsBrand(GoodsBrandVo goodsBrandVo) {
        long count = goodsBrandMapper.isGoodsBrandExists(goodsBrandVo.getBtype());
        if (count > 0) {
            return AjaxResult.defeated("对不起，商品品牌已存在");
        }
        int i = goodsBrandMapper.addGoodsBrand(goodsBrandVo);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.defeated();
    }

    @Override
    public AjaxResult getGoodsBrand(int id) {
        GoodsBrandVo r = goodsBrandMapper.getGoodsBrand(id);
        servletContext.setAttribute("currentUpdateGoodsBrand",r);
        return AjaxResult.success(r);
    }

    @Override
    public AjaxResult updateGoodsBrand(GoodsBrandVo goodsBrandVo) {
        GoodsBrandVo currentUpdateGoodsBrand = (GoodsBrandVo) servletContext.getAttribute("currentUpdateGoodsBrand");

        if (!goodsBrandVo.getId().equals(currentUpdateGoodsBrand.getId())){
            return AjaxResult.defeated("不可以乱改哦");

        }
        long count = goodsBrandMapper.isUpdateGoodsBrandExists(goodsBrandVo);

        if (count > 0) {
            return AjaxResult.defeated("已存在该商品品牌");
        }

        int i = goodsBrandMapper.updateGoodsBrand(goodsBrandVo);

        if (i > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.defeated();
    }

    @Override
    public AjaxResult deleteGoodsBrand(int id) {
        int  r = goodsBrandMapper.deleteGoodsBrand(id);
        servletContext.setAttribute("currentUpdateGoodsBrand",r);
        return AjaxResult.success(r);
    }
}
